﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.DirectShow.Filters;
using System.IO;

namespace System.Windows.Media.DirectShow.Filters
{
    public class FileWriterInputPin : BaseInputPin
    {
        private AMMediaType[] _mediaTypes = new AMMediaType[] { new AMMediaType {
            MajorType = MediaMajorTypes.Stream,
            SubType = MediaSubTypes.None,
        }};

        private Stream fileStream;

        public FileWriterInputPin(IBaseFilter filter)
            : base(filter)
        {

        }

        internal Stream FileStream
        {
            get
            {
                return fileStream;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException();
                if (!value.CanWrite || !value.CanSeek)
                    throw new ArgumentException("Stream must be seekable and writeable");

                fileStream = value;
                fileStream.Seek(0, SeekOrigin.Begin);
            }
        }

        public override bool ReceiveCanBlock
        {
            get { return true; }
        }

        protected override void Receive(IMediaSample sample)
        {
            sample.AddRef();

            try
            {
                if (this.fileStream != null)
                {
                    this.fileStream.Seek(sample.StartMediaTime, SeekOrigin.Begin);
                    this.fileStream.Write(sample.Data, 0, (int)sample.Length);
                }
            }
            finally
            {
                sample.Release();
            }
        }

        protected override AllocatorProperties GetAllocatorRequirements()
        {
            return new AllocatorProperties { BuffersCount = 8, BufferSize = 1000 };
        }

        public override void Inactive()
        {
            base.Inactive();

            // Close the header
            this.FileStream.Flush();
        }

        protected override void EndOfStream()
        {
            base.EndOfStream();

            // Close the header
            this.FileStream.Flush();

            // Notify completed
            ((IMediaEvent)this.Filter.Graph).NotifyEvent(new MediaEventArgs(this.Filter, MediaNotification.Completed));
        }

        public override System.Collections.Generic.IEnumerable<AMMediaType> MediaTypes
        {
            get { return _mediaTypes; }
        }

        public override string Name
        {
            get { return "Input stream"; }
        }
    }
}
